//
//  NewFeatureView.swift
//  MXWeiBo
//
//  Created by Apple on 16/2/26.
//  Copyright © 2016年 Applea. All rights reserved.
//

import UIKit
import SnapKit
//新特性图像数量
private let MXNewFeatureImgCount = 4
class NewFeatureView: UIView {
    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        setupNewView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        print("\(classForCoder)\(__FUNCTION__)")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        removeFromSuperview()
    }
//   MARK:  --私有属性
    private lazy var pageControl = UIPageControl()
}
//    MARK:  --设置界面
extension NewFeatureView {

   func setupNewView()
   {
//    1.使用scrollview
      let scrollow = UIScrollView(frame: bounds)
    addSubview(scrollow)
//    2.添加图片
    for i in 0..<MXNewFeatureImgCount{
     
        let imgName = "new_feature_\(i+1)"
        let iv = UIImageView(image: UIImage(named: imgName))
//        设置frame
        iv.frame = CGRectOffset(bounds, CGFloat(i) * bounds.width, 0)
        scrollow.addSubview(iv)
    }
    
//    3.设置 contentsize:可以滚动的区域 ，多加一页，保证最后一页仍然可以滚动
    scrollow.contentSize = CGSize(width: CGFloat(MXNewFeatureImgCount + 1)*bounds.width, height: 0)
    
//    4.设置其他属性
//    是否反弹
    scrollow.bounces = false
//    是否滚动
    scrollow.showsHorizontalScrollIndicator = false
//    是否翻页
    scrollow.pagingEnabled = true
    
//   5.设置分页控件
    addSubview(pageControl)
//    设置执行完之后在更新小数点页数
    pageControl.hidesForSinglePage = true
//    设置点点个数
    pageControl.numberOfPages = MXNewFeatureImgCount
//    设置颜色
    pageControl.pageIndicatorTintColor = UIColor.blackColor()
    pageControl.currentPageIndicatorTintColor=MXAppearanceTintColor
//    禁止用户交互
    pageControl.userInteractionEnabled = false
//    6.自动布局
    pageControl.snp_makeConstraints { (make) -> Void in
        make.centerX.equalTo(self)
        make.bottom.equalTo(self).offset(-60)
    }
//    7.设置代理
    scrollow.delegate = self
    }
  
}
extension NewFeatureView: UIScrollViewDelegate {

    func scrollViewDidEndDecelerating(scrollow : UIScrollView) {
//    1.计算当前所在页
        let page = Int(scrollow.contentOffset.x / scrollow.bounds.width)
//    2.如果是最后一页，销毁当前的视图
        if page == MXNewFeatureImgCount {
           removeFromSuperview()
        }
    
    }
    
//    只要滚动视图发生滚动就会被调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = page
        
//        如果是最后一页，隐藏分页控件
        pageControl.hidden = (page == MXNewFeatureImgCount)
     }
    
}